import axios from 'axios';

export default {
  /**
   * 发送POST请求的异步函数
   * 该函数主要用于处理文本数据，生成语音音频，并创建相应的音频源
   * @param {Object} data 包含请求相关数据的对象
   * @returns {Object} 返回处理后的数据对象，包括音频源和音频初始化状态
   */
  async sendPostRequestApi(data) {
    // 腾讯云API签名v3实现示例
    // 本代码基于腾讯云API签名v3文档实现: https://cloud.tencent.com/document/product/213/30654
    // 请严格按照文档说明使用，不建议随意修改签名相关代码
    // 打印接收到的数据，便于调试
    // console.log("sendPostRequest001打印数据：", data)

    // 初始化返回数据对象
    let returnD = data
    returnD.audioInit = false
    returnD.isAudioStart = { id: data.msg_i, is: false }

    // 如果是整体执行模式
    if (data.all) {
      // 如果是第一次执行
      if (data.to_i === -1) {
        // 初始化音频状态
        returnD.audioInit = true
        data.to_i++
      }
      // 分割消息内容，以便逐段处理
      let msgArr = data.msg_content.split(data.toSpeechtest)
      // console.log("currentMessages", data.msg_content,data.toSpeechtest)
      // console.log("toSpeechKey", data.to_i, msgArr)

      // 更新文本内容
      data.text = msgArr[data.to_i]
      // 如果没有文本内容，则返回false
      if (!data.text) {
        return false
      }
    }
    // 如果文本内容为空，则打印错误并返回false
    if (!data.text.length) {
      console.error("text无数据",data)
      console.error("text无数据")
      return false
    }

    // 创建包含文本和音频源的对象
    let toSArr = { id: data.to_i, src: '', text: data.text }
    returnD.audioSrc = toSArr


    // 处理文本，替换特殊字符和空格为逗号
    let modifiedText = data.text.replace(/\*/g, ',').replace(/\|/g, ',').replace(/-/g, ',')
    modifiedText = modifiedText.replace(/\s+/g, ' ').replace(/ {2,}/g, ', ')

    // ************* 步骤 0：配置+准备语音合成 *************

    const https = require("https")
    const crypto = require("crypto")

    function sha256(message, secret = "", encoding) {
      const hmac = crypto.createHmac("sha256", secret)
      return hmac.update(message).digest(encoding)
    }
    function getHash(message, encoding = "hex") {
      const hash = crypto.createHash("sha256")
      return hash.update(message).digest(encoding)
    }
    function getDate(timestamp) {
      const date = new Date(timestamp * 1000)
      const year = date.getUTCFullYear()
      const month = ("0" + (date.getUTCMonth() + 1)).slice(-2)
      const day = ("0" + date.getUTCDate()).slice(-2)
      return `${year}-${month}-${day}`
    }

    // 密钥信息从环境变量读取，需要提前在环境变量中设置 TENCENTCLOUD_SECRET_ID 和 TENCENTCLOUD_SECRET_KEY
    // 使用环境变量方式可以避免密钥硬编码在代码中，提高安全性
    // 生产环境建议使用更安全的密钥管理方案，如密钥管理系统(KMS)、容器密钥注入等
    // 请参见：https://cloud.tencent.com/document/product/1278/85305
    // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
    const SECRET_ID = 'AKIDBG9oHYbPyJRM2ThhS1NXTJ1mLi2ECylQ'
    const SECRET_KEY = 'WosiL4czA7sRmtoX4NSL0RecNvHQN6aq'
    const TOKEN = ""

    const host = window.location.host + "/ttsapi"
    console.log("host",window.location)
    // const host = "/ttsapi"
    const service = "tts"
    const region = "ap-beijing"
    const action = "TextToVoice"
    const version = "2019-08-23"
    const timestamp = parseInt(String(new Date().getTime() / 1000))
    const date = getDate(timestamp)
    // 502001   智小柔  超自然
    // 601005   601010  大模型
    // 301037   101027  精品
    const payload = JSON.stringify({
      Text: modifiedText,
      SessionId: "session-1234",
      Volume: 1,
      Speed: 0,
      ProjectId: 0,
      ModelType: 1,
      VoiceType: 101027,
      PrimaryLanguage: 1,
      SampleRate: 16000,
      Codec: "wav",
      EnableSubtitle: true,
      SegmentRate: 0,
      EmotionCategory: "neutral",
      EmotionIntensity: 100
    });
    // ************* 步骤 1：拼接规范请求串 *************
    const signedHeaders = "content-type;host"
    const hashedRequestPayload = getHash(payload)
    const httpRequestMethod = "POST"
    const canonicalUri = "/"
    const canonicalQueryString = ""
    const canonicalHeaders =
      "content-type:application/json; charset=utf-8\n" + "host:" + "tts.tencentcloudapi.com" + "\n"
    // console.log(window.location)
    const canonicalRequest =
      httpRequestMethod +
      "\n" +
      canonicalUri +
      "\n" +
      canonicalQueryString +
      "\n" +
      canonicalHeaders +
      "\n" +
      signedHeaders +
      "\n" +
      hashedRequestPayload
    console.log("canonicalRequest",canonicalRequest)
    // ************* 步骤 2：拼接待签名字符串 *************
    const algorithm = "TC3-HMAC-SHA256"
    const hashedCanonicalRequest = getHash(canonicalRequest)
    const credentialScope = date + "/" + service + "/" + "tc3_request"
    const stringToSign =
      algorithm +
      "\n" +
      timestamp +
      "\n" +
      credentialScope +
      "\n" +
      hashedCanonicalRequest
      console.log("stringToSign",stringToSign)

    // ************* 步骤 3：计算签名 *************
    const kDate = sha256(date, "TC3" + SECRET_KEY)
    const kService = sha256(service, kDate)
    const kSigning = sha256("tc3_request", kService)
    const signature = sha256(stringToSign, kSigning, "hex")

    // ************* 步骤 4：拼接 Authorization *************
    const authorization =
      algorithm +
      " " +
      "Credential=" +
      SECRET_ID +
      "/" +
      credentialScope +
      ", " +
      "SignedHeaders=" +
      signedHeaders +
      ", " +
      "Signature=" +
      signature

    // ************* 步骤 5：构造并发起请求 *************
    const headers = {
      "Authorization": authorization,
      "Content-Type": "application/json; charset=utf-8",
      // Host: host,
      "X-TC-Action": action,
      "X-TC-Timestamp": timestamp,
      "X-TC-Version": version,
    }
    // console.log("headers", headers)

    if (region) {
      headers["X-TC-Region"] = region
    }
    if (TOKEN) {
      headers["X-TC-Token"] = TOKEN
    }

    const options = {
      hostname: window.location.hostname,
      port: window.location.port,
      path: '/ttsapi',
      method: httpRequestMethod,
      headers,

    }
    console.log("options",options)

    // console.log("host", host)
    // console.log("options", options)

    // 使用axios发送POST请求，测试成功，平均速度1秒以上
    const dataArr = await axios.post(window.location.protocol+'//' + window.location.host + '/ttsapi', payload, options)
    console.log("dataArr", dataArr)
    // return 
    // const dataArr = JSON.parse(response)
    // console.log("end", dataArr.Response)
    // console.log("end", dataArr.data.Response.Audio)
    const audioBase64 = dataArr.data.Response.Audio; // 假设返回的是纯 Base64 字符串

    // 2. 关键：将 Base64 转为 Blob（浏览器正确用法）
    const byteCharacters = atob(audioBase64); // 解码 Base64
    const byteNumbers = new Array(byteCharacters.length);

    for (let i = 0; i < byteCharacters.length; i++) {
      byteNumbers[i] = byteCharacters.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);

    const audioBlob = new Blob([byteArray], { type: 'audio/wav' })
    let blobSrc = URL.createObjectURL(audioBlob)

    // 如果成功创建音频源
    if (blobSrc) {
      returnD.audioSrc.src = blobSrc

      // 根据条件设置音频播放状态
      // console.log("根据条件设置音频播放状态:",data.to_i,this.audioAutoKey,this.isAutoAudio)
      if (data.to_i === 0 && !this.audioAutoKey && !this.isAutoAudio) {
        returnD.isAudioStart.is = true
        returnD.audioStart = true
      }
    }
    // 返回处理后的数据对象
    console.log("returnD", returnD)
    return returnD


    // 使用https发送POST请求，测试成功，平均速度700毫秒
    const req = https.request(options, (res) => {
      let data = ""
      res.on("data", (chunk) => {
        data += chunk
        // console.log("chunk:", chunk)
      })

      res.on("end", () => {
        const dataArr = JSON.parse(data)
        // console.log("end", dataArr.Response)
        console.log("end", dataArr.Response.Audio)
        const mp3Data = dataArr.Response.Audio
        const audioBlob = new Blob([mp3Data], { type: 'audio/mpeg' })
        let blobSrc = URL.createObjectURL(audioBlob)

        // 如果成功创建音频源
        if (blobSrc) {
          returnD.audioSrc.src = blobSrc

          // 根据条件设置音频播放状态
          // console.log("根据条件设置音频播放状态:",data.to_i,this.audioAutoKey,this.isAutoAudio)
          if (data.to_i === 0 && !this.audioAutoKey && !this.isAutoAudio) {
            returnD.isAudioStart.is = true
            returnD.audioStart = true
          }
        }
        // 返回处理后的数据对象
        console.log(returnD)
        return returnD
      })
    })

    req.on("error", (error) => {
      console.error(error)
    })

    req.write(payload)

    req.end()

  }

};
